package com.compty.paint.web.member;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.compty.core.framework.image.ImageUtils;
import com.compty.core.framework.util.FileUtil;
import com.compty.core.framework.util.StringUtil;
import com.compty.core.struts2.BaseAction;
import com.compty.core.utils.CommonsUtil;
import com.compty.paint.domain.ImageInfo;
import com.compty.paint.manager.ImageInfoManager;

/**
 * 文件上传
 * sharpId 1:表示正方形 2：表示长方形(竖),3：表示长方形(横),4：表示长卷(横披),5:长卷(立轴),6:表示头像,7:表示展览海报
 * 8:表示背景摆设  9:表示画廊logo 10:表示拍卖画册封面 11:表示瓷艺正方形 12：瓷艺长方形(竖)13：瓷艺长方形(横)
 * @CreateTime:2011-7-4 上午09:54:05
 */
public class FileUploadAction extends BaseAction<Object> {

	private static final long serialVersionUID = -3791018165063039099L;
	private static Log log = LogFactory.getLog(FileUploadAction.class);
   
    private File myFile;
    private String fileName;//图片原始名字
    private String imageFileName;//重命名后的图片名字
    private ImageInfoManager imageInfoManager;
    private int imgWidth;
    private int imgHeight;
    private String imgType; //图片种类，(艺术家、作品、海报)
    private String sharpId;
   
    public void setMyFileFileName(String fileName)  {
        this.fileName = fileName;
    }
       
    public String getFileName() {
		return fileName;
	}

	public File getMyFile() {
		return myFile;
	}

	public void setMyFile(File myFile)  {
        this.myFile = myFile;
    } 
    
    public String getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}

	public void setImageInfoManager(ImageInfoManager imageInfoManager) {
		this.imageInfoManager = imageInfoManager;
	}
	
	public int getImgWidth() {
		return imgWidth;
	}

	public void setImgWidth(int imgWidth) {
		this.imgWidth = imgWidth;
	}

	public int getImgHeight() {
		return imgHeight;
	}

	public void setImgHeight(int imgHeight) {
		this.imgHeight = imgHeight;
	}

	public String getImgType() {
		return imgType;
	}

	public void setImgType(String imgType) {
		this.imgType = imgType;
	}
	
	public String getSharpId() {
		return sharpId;
	}

	public void setSharpId(String sharpId) {
		this.sharpId = sharpId;
	}
	
	/**
	 * sharpId 1:表示正方形 2：表示长方形(竖),3：表示长方形(横),4：表示长卷(横披),5:长卷(立轴),6:表示头像,7:表示展览海报
	 * 8:表示背景摆设  9:表示画廊logo 10:表示拍卖画册封面
	 */
    @Override
	public String execute() {
    	
		if (myFile != null) {
			String newImageFileName = getRandomImageFileName();
			imageFileName = newImageFileName + "."+ StringUtil.getExt(fileName) ;
			String srcpath = getImageUploadPath()+ CommonsUtil.getPathSymbol() + imageFileName;
			File imageFile = new File(srcpath);
			FileUtil.copy(myFile, imageFile);
			
			try {
				Long sharp_id = sharpId != null ? Long.valueOf(sharpId):0l;
				
				String flag = ImageUtils.checkImageSharp(srcpath,sharpId);
				String errorMessage = "";
				if(1 == sharp_id ){//正方形
					errorMessage = "您选择的是正方形形状，";
				}
				else if(2 == sharp_id ){//长方形(竖)
					errorMessage = "您选择的是长方形(竖)形状，";
				}
				else if(3 == sharp_id ){//长方形(横)
					errorMessage = "您选择的是长方形(横)形状，";
				}
				else if(4 == sharp_id ){//长卷(横披)
					errorMessage = "您选择的是长卷(横披)形状，";
				}
				else if(5 == sharp_id ){//长卷(立轴)
					errorMessage = "您选择的是长卷(立轴)形状，";
				}
				else if(6 == sharp_id ){//头像
					errorMessage = "您选择的是头像形状，";
				}
				else if(7 == sharp_id ){//展览
					errorMessage = "您选择的是展览海报形状，";
				}
				if( (sharp_id == 1 || sharp_id == 2 || sharp_id == 3 || sharp_id == 4 || sharp_id == 5) &&  flag != null  ){
					imageFileName = "";
					if("1".equals(flag)){
						addFieldError("imageStyle", errorMessage+"该图片尺寸符合正方形形状。");
					}else if("2".equals(flag)){
						addFieldError("imageStyle", errorMessage+"该图片尺寸符合长方形(横)形状。");
					}else if("3".equals(flag)){
						addFieldError("imageStyle", errorMessage+"该图片尺寸符合长方形(竖)形状。");
					}
					
					return INPUT;
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return SUCCESS;
		}
		return INPUT;
	}
    
    /**
     *@Todo:上传头像
     *@CreateTime:2011-9-8 下午02:47:58
     */
	public String uploadHeadPhoto() {
    	
		if (myFile != null) {
			
			uploadImageFile();
			
			return "headPhoto_upload_success";
		}
		
		return "headPhoto_upload_error";
	}
	
	  /**
     *@Todo:上传展览封面
     *@CreateTime:2011-9-8 下午02:47:58
     */
	public String uploadExhibitionCoverPhoto() {
    	
		if (myFile != null) {
			
			uploadImageFile();
			
			return "exhibitionCover_upload_success";
		}
		
		return "exhibitionCover_upload_error";
	}
    
    
    /**
     * 上传摆设背景图片至服务器
     *@author:zhuqh
     *@CreateTime:2011-7-13 上午11:11:01
     */
    public String uploadBackgroundImage() {
    	
    	if ( myFile != null) {
    		
    		uploadImageFile();
			
			request.setAttribute("ajaxData", imageFileName);
        }
    	
    	return "saveImageSuccess";
    }
    
    /**
     * 上传图片准备
     */
    public String uploadPrepare(){
    	
    	if("painter".equals(imgType)){
    		this.imgWidth = 147;
    		this.imgHeight = 181;
    		return "headPhoto_upload_prepare";
    	}
    	else if("exhibition".equals(imgType)){
    		this.imgWidth = 210;
    		this.imgHeight = 280;
    		return "exhibitionCover_upload_prepare";
    	}
    	else if("gallery".equals(imgType)){
    		this.imgWidth = 165;
    		this.imgHeight = 217;
    	}
    	else if("auction".equals(imgType)){
    		this.imgWidth = 165;
    		this.imgHeight = 217;
    	}
    	else if("painting".equals(imgType)){
    		if("1" == sharpId){
    			this.imgWidth = 580;
        		this.imgHeight = 384;
    		}
    		else if("2" == sharpId){
    			this.imgWidth = 580;
        		this.imgHeight = 384;
    		}
    		else if("3" == sharpId){
    			this.imgWidth = 580;
        		this.imgHeight = 384;
    		}
    		else if("4" == sharpId){
    			this.imgWidth = 580;
        		this.imgHeight = 384;
    		}
    		else if("5" == sharpId){
    			this.imgWidth = 580;
        		this.imgHeight = 384;
    		}else{
    			this.imgWidth = 580;
        		this.imgHeight = 384;
    		}
    	}
    	
    	return "uploadPrepare";
    }
    
    /**
     *@Todo:保存裁剪后的图片
     *@author:zhuqh
     *@CreateTime:2011-7-4 下午12:42:35
     * @return
     * @throws Exception 
     * @throws NumberFormatException 
     */
    public String saveImage() throws NumberFormatException, Exception{
    	
    	String pic = request.getParameter("p"); //图片名称
    	int PointX = Integer.parseInt(request.getParameter("x"));
    	int PointY =Integer.parseInt(request.getParameter("y"));
    	int CutWidth = Integer.parseInt(request.getParameter("w"));
    	int CutHeight = Integer.parseInt(request.getParameter("h"));
    	int PicWidth =  Integer.parseInt(request.getParameter("pw"));
    	int PicHeight = Integer.parseInt(request.getParameter("ph"));
    	String originalName = request.getParameter("fileName");
    	String sharpId = request.getParameter("sharpId");
    	
    	String imageFilePath = getImageUploadPath()+CommonsUtil.getPathSymbol() + pic; //图片物理路径
    	
		try {
			BufferedImage bufferedImage = ImageIO.read(new File(imageFilePath));
			int x = PointX * bufferedImage.getWidth()/PicWidth;
	    	int y = PointY * bufferedImage.getHeight()/PicHeight;
	    	int width = CutWidth * bufferedImage.getWidth()/PicWidth;
	    	int height = CutHeight * bufferedImage.getHeight()/PicHeight;
	    	
	    	ImageUtils.cut(imageFilePath,imageFilePath, x, y, width, height); //先裁剪
	    	ImageUtils.scaleImage(imageFilePath, imageFilePath, Long.valueOf(sharpId)); //再缩放
	    	
	    	File file = new File(imageFilePath);
	    	ImageInfo image = saveImageToDB(file,originalName,sharpId,pic,null);
	    	log.debug("imageId====="+image.getId());
	    	
	    	bufferedImage = ImageIO.read(new File(imageFilePath));
	    	int realWidth = bufferedImage.getWidth();
	    	int realHeight = bufferedImage.getHeight();
	    	
	    	request.setAttribute("ajaxData", image.getId()+","+ image.getSuffix()+","+realWidth+","+realHeight);
	    	
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
    	return "saveImageSuccess";
    }
    
    /**
     *@Todo:保存艺术家头像
     *@CreateTime:2011-9-7 下午05:52:51
     * @return
     * @throws Exception 
     * @throws NumberFormatException 
     */
    public String saveHeadPhoto() throws NumberFormatException, Exception{
    	
    	String pic = request.getParameter("p"); //图片名称
    	int PointX = Integer.parseInt(request.getParameter("x"));
    	int PointY =Integer.parseInt(request.getParameter("y"));
    	int CutWidth = Integer.parseInt(request.getParameter("w"));
    	int CutHeight = Integer.parseInt(request.getParameter("h"));
    	int PicWidth =  Integer.parseInt(request.getParameter("pw"));
    	int PicHeight = Integer.parseInt(request.getParameter("ph"));
    	String originalName = request.getParameter("fileName");
    	String sharpId = request.getParameter("sharpId");
    	
    	String imageFilePath = getImageUploadPath()+CommonsUtil.getPathSymbol() + pic; //图片物理路径
    	
		try {
			BufferedImage bufferedImage = ImageIO.read(new File(imageFilePath));
			int x = PointX * bufferedImage.getWidth()/PicWidth;
	    	int y = PointY * bufferedImage.getHeight()/PicHeight;
	    	int width = CutWidth * bufferedImage.getWidth()/PicWidth;
	    	int height = CutHeight * bufferedImage.getHeight()/PicHeight;
	    	
	    	ImageUtils.cut(imageFilePath,imageFilePath, x, y, width, height);//先裁剪
	    	ImageUtils.scaleImage(imageFilePath, imageFilePath, Long.valueOf(sharpId));//再缩放
	    	
	    	File file = new File(imageFilePath);
	    	ImageInfo image = saveImageToDB(file,originalName,sharpId,pic,"headphoto");
	    	log.debug("imageId====="+image.getId());
	    
	    	request.setAttribute("ajaxData", image.getId().toString()+","+ image.getSuffix());
	    	
		} catch (IOException e) {
			e.printStackTrace();
		}
		
    	return "headPhoto_saved";
    }
    
    /**
     *@Todo:保存展览封面
     *@CreateTime:2011-9-7 下午05:52:51
     * @return
     * @throws Exception 
     * @throws NumberFormatException 
     */
    public String saveExhibitionCoverPhoto() throws NumberFormatException, Exception{
    	
    	String pic = request.getParameter("p"); //图片名称
    	int PointX = Integer.parseInt(request.getParameter("x"));
    	int PointY =Integer.parseInt(request.getParameter("y"));
    	int CutWidth = Integer.parseInt(request.getParameter("w"));
    	int CutHeight = Integer.parseInt(request.getParameter("h"));
    	int PicWidth =  Integer.parseInt(request.getParameter("pw"));
    	int PicHeight = Integer.parseInt(request.getParameter("ph"));
    	String originalName = request.getParameter("fileName");
    	String sharpId = request.getParameter("sharpId");
    	
    	String imageFilePath = getImageUploadPath()+CommonsUtil.getPathSymbol()+ pic; //图片物理路径
    	
		try {
			BufferedImage bufferedImage = ImageIO.read(new File(imageFilePath));
			int x = PointX * bufferedImage.getWidth()/PicWidth;
	    	int y = PointY * bufferedImage.getHeight()/PicHeight;
	    	int width = CutWidth * bufferedImage.getWidth()/PicWidth;
	    	int height = CutHeight * bufferedImage.getHeight()/PicHeight;
	    	
	    	ImageUtils.cut(imageFilePath,imageFilePath, x, y, width, height);//先裁剪
	    	ImageUtils.scaleImage(imageFilePath, imageFilePath, Long.valueOf(sharpId));//再缩放
	    	
	    	File file = new File(imageFilePath);
	    	ImageInfo image = saveImageToDB(file,originalName,sharpId,pic,"exhibitioncover");
	    	log.debug("imageId====="+image.getId());
	    
	    	request.setAttribute("ajaxData", image.getId().toString()+","+ image.getSuffix());
	    	
		} catch (IOException e) {
			e.printStackTrace();
		}
		
    	return "exhibitionCover_saved";
    }
    
    /************* 保存图片至 数据库 *******************/
    public ImageInfo saveImageToDB(File file,String originalName,String sharpId,String newNameUploaded,String memo){
		ImageInfo imageInfo = buildImage(file,originalName,sharpId,newNameUploaded,memo);
    	imageInfoManager.save(imageInfo);
    	imageInfoManager.clear();
    	return imageInfo;
    }
    
    /**
     * 将本地图片拷贝至服务器
     */
    private void uploadImageFile(){
    	
		String newImageFileName = getRandomImageFileName();
		imageFileName = newImageFileName + "."+ StringUtil.getExt(fileName) ;
		String srcpath = getImageUploadPath()+ CommonsUtil.getPathSymbol() + imageFileName;
		File imageFile = new File(srcpath);
		
		FileUtil.copy(myFile, imageFile);
    }
}
